package com.shoeshopping.action.joseph;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.interceptor.SessionAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.shoeshopping.entity.User;
import com.shoeshopping.formbean.joseph.UserForm;
import com.shoeshopping.service.joseph.UserService;
import com.shoeshopping.utils.joseph.Result;
import com.shoeshopping.utils.joseph.UserForm2User;

@Controller("userAction")
public class UserAction extends ActionSupport  implements ModelDriven<UserForm>, SessionAware{
	private UserForm userForm = new UserForm();
	private User user;
	private UserService userService;
	private Map<String, Object> session;
	//注册
	public String register(){
		//先判断输入的用户信息是否可以注册
		if(userForm.canBeRegister()){
			//将UserForm对象转换成User对象
			User userTmp = UserForm2User.toUser(userForm);
			boolean flag = userService.checkRegister(userTmp);
			if(flag)
				return Result.REGISTER_SUCCESS;
			else {
				session.put("errorMsg", "用户名已注册!");
				return  Result.REGISTER_FAILURE;
			}
		}else{
		session.put("errorMsg", "用户信息不全！");
		return  Result.REGISTER_FAILURE;
		}
	}
	
	//登陆
	public String login(){
		user = UserForm2User.toUser(userForm);

		User loginUser = userService.checkLogin(user);
		if(loginUser!=null){
			session.put("user", loginUser);

			session.put("username", loginUser.getUsername());

			return Result.LOGIN_SUCCESS;
		}
		else{
			session.put("errorMsg", "用户名或者密码错误，登陆失败！");
			return Result.LOGIN_FAILURE;
		}
	}
	public String exit(){
		session.remove("user");
		session.remove("username");
		return Result.LOGIN;
	}
	public String toModify(){
		return Result.MODIFY_PAGE;
	}
	public String modify(){
		User currentUser = (User)session.get("user");
		if(currentUser==null || !userForm.isSamePassoword()){
			session.put("errorMsg", "两次密码不一致！");
			return Result.MODIFY_FAILURE;
		}
		else {
			currentUser.setEmail(userForm.getEmail());
			currentUser.setPassword(userForm.getPassword());
			userService.modify(currentUser);
			session.remove("user");
			session.remove("username");
			return Result.MODIFY_SUCCESS;
		}
	}
	
	@Resource(name="userService")
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	@Override
	public void setSession(Map<String, Object> session) {
			this.session = session;
	}
	public UserService getUserService() {
		return userService;
	}
	public UserForm getUserForm() {
		return userForm;
	}
	public void setUserForm(UserForm userForm) {
		this.userForm = userForm;
	}
	@Override
	public UserForm getModel() {
		return userForm;
	}

	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public Map<String, Object> getSession() {
		return session;
	}
	
}
